const mongoose = require('../model/db');
const { userModel, MessageModel, ConversationModel, Schoolmodel } = require('../model/model');

async function checkData() {
    try {
        console.log('🔍 检查数据库数据...');

        // 等待数据库连接
        await new Promise(resolve => {
            if (mongoose.connection.readyState === 1) {
                resolve();
            } else {
                mongoose.connection.once('connected', resolve);
            }
        });

        console.log('✅ 数据库连接成功\n');

        // 检查学校数据
        const schools = await Schoolmodel.find({});
        console.log('🏫 === 学校数据 ===');
        console.log(`学校总数: ${schools.length}`);
        schools.forEach((school, index) => {
            console.log(`${index + 1}. ${school.name} (${school.abbreviation}): ${school._id.toString()}`);
        });

        // 检查用户数据
        const users = await userModel.find({}).populate('schoolId', 'name');
        console.log('\n👥 === 用户数据 ===');
        console.log(`用户总数: ${users.length}`);
        users.forEach((user, index) => {
            console.log(`${index + 1}. ${user.username} (${user.studentId})`);
            console.log(`   ID: ${user._id.toString()}`);
            console.log(`   学校: ${user.schoolId ? user.schoolId.name : '未知'}`);
            console.log(`   签名: ${user.qianming || '无'}`);
            console.log(`   头像: ${user.isAvatarImageSet ? '已设置' : '未设置'}`);
            console.log('   ---');
        });

        // 检查消息数据
        const messages = await MessageModel.find({}).populate('senderId', 'username').populate('receiverId', 'username');
        console.log('\n💬 === 消息数据 ===');
        console.log(`消息总数: ${messages.length}`);
        if (messages.length > 0) {
            messages.slice(0, 5).forEach((message, index) => {
                console.log(`${index + 1}. ${message.senderId?.username || '未知'} → ${message.receiverId?.username || '未知'}`);
                console.log(`   内容: ${message.content}`);
                console.log(`   时间: ${message.timestamp}`);
                console.log('   ---');
            });
            if (messages.length > 5) {
                console.log(`... 还有 ${messages.length - 5} 条消息`);
            }
        }

        // 检查会话数据
        const conversations = await ConversationModel.find({}).populate('participants', 'username');
        console.log('\n🤝 === 会话数据 ===');
        console.log(`会话总数: ${conversations.length}`);
        conversations.forEach((conversation, index) => {
            console.log(`${index + 1}. 会话ID: ${conversation._id.toString()}`);
            console.log(`   参与者: ${conversation.participants.map(p => p.username).join(', ')}`);
            console.log(`   最后消息时间: ${conversation.lastMessageTime}`);
            console.log(`   未读消息数: ${conversation.unreadCount}`);
            console.log('   ---');
        });

        // 按学校分组统计用户
        const usersBySchool = {};
        users.forEach(user => {
            const schoolName = user.schoolId ? user.schoolId.name : '未知学校';
            if (!usersBySchool[schoolName]) {
                usersBySchool[schoolName] = [];
            }
            usersBySchool[schoolName].push(user);
        });

        console.log('\n📊 === 按学校分组的用户统计 ===');
        Object.keys(usersBySchool).forEach(schoolName => {
            console.log(`\n${schoolName} (${usersBySchool[schoolName].length}人):`);
            usersBySchool[schoolName].forEach(user => {
                console.log(`  - ${user.username} (${user.studentId})`);
            });
        });

        // 数据健康检查
        console.log('\n🔍 === 数据健康检查 ===');
        
        // 检查孤立用户（没有对应学校的用户）
        const orphanUsers = users.filter(user => !user.schoolId);
        if (orphanUsers.length > 0) {
            console.log(`⚠️  发现 ${orphanUsers.length} 个孤立用户（没有学校信息）`);
        } else {
            console.log('✅ 所有用户都有学校信息');
        }

        // 检查空用户名
        const emptyUsernameUsers = users.filter(user => !user.username || user.username.trim() === '');
        if (emptyUsernameUsers.length > 0) {
            console.log(`⚠️  发现 ${emptyUsernameUsers.length} 个用户没有用户名`);
        } else {
            console.log('✅ 所有用户都有用户名');
        }

        // 检查重复学号
        const studentIds = users.map(user => user.studentId);
        const duplicateStudentIds = studentIds.filter((id, index) => studentIds.indexOf(id) !== index);
        if (duplicateStudentIds.length > 0) {
            console.log(`⚠️  发现重复学号: ${[...new Set(duplicateStudentIds)].join(', ')}`);
        } else {
            console.log('✅ 没有重复的学号');
        }

        console.log('\n🎉 数据检查完成！');
        process.exit(0);

    } catch (error) {
        console.error('❌ 检查数据失败:', error);
        process.exit(1);
    }
}

// 运行脚本
checkData(); 